//
//  JJTools.swift
//  微博1
//
//  Created by 卷卷 on 15/9/1.
//  Copyright © 2015年 JJ. All rights reserved.
//**
/**
App key：2834416211
App secret：1a8a95cebed5782eaa467552f63a5ed2

https://api.weibo.com/oauth2/authorize?client_id=2834416211&redirect_uri=http://www.itheima.com


获得的回调获得授权地址：http://www.itheima.com/?code=33c762c5c10dbfb183f5ace0c4e6c1e6


http://itheima.com/?code=bfe3a836a53a422d8acdf9553636d04e


client_id 	true 	string 	申请应用时分配的AppKey。
client_secret 	true 	string 	申请应用时分配的AppSecret。
grant_type 	true 	string 	请求的类型，填写authorization_code


grant_type为authorization_code时

必选 	类型及范围 	说明
code 	true 	string 	调用authorize获得的code值。
redirect_uri 	true 	strin

juanjuan[85006:3454931] 请求成功－－{
"access_token" = "2.008OtLZFVIvoFD497a54708a0cwJNl";
"expires_in" = 157679999;
"remind_in" = 157679999;
uid = 5100669843;
}

*/


import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String {
    
    case GET = "GET"
    case POST = "POST"
}

//网络工具类
class JJNetwokingTools: AFHTTPSessionManager {
    
   //MARK：App 信息
    private let clientId = "2834416211"
    private let appSecret = "1a8a95cebed5782eaa467552f63a5ed2"
    
    //回调地址
    let redirectUri = "http://www.itheima.com"
    
    //单例
    static let shareTools:JJNetwokingTools = {
        
        //指定 baseUrl
        var instance = JJNetwokingTools(baseURL: nil)
        
        //设置反序列化的支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return instance
    }()
    
    // MARK：－OAuth
    // OAuth 授权 URL
    //- see: [http://open.weibo.com/wiki/Oauth2/authorize]
    var oauthUrl:NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&client_secret=\(clientId)"
        
        return NSURL(string: urlString)!
    }
    
    
    //MARK：－微博数据
    //加载微博数据
    //－returns：RAC Signal
    //- see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatues() ->RACSignal {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        return request(.GET, URLString: urlString, parameters: nil)
    }
    
    
    //获取AccessToken
    
    ////parameters：参数字典code: 请求码／授权码
    //- see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccessToken(code:String) -> RACSignal{
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        return request(.POST, URLString: urlString, parameters: params)
    }
    
    //加载用户信息
    // uid : uid
    // returns : RAC Siganl
    // - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    
    func loadUserInfo(uid:String) ->
        RACSignal{
            
            let urlString = "https://api.weibo.com/2/users/show.json"
            let params = ["uid": uid]
            
            return request(.GET, URLString: urlString, parameters: params)
    }
    
    //网络请求方法
    
    //method：method
    //Urlstring：URLString
    //－returns：RAC c cSignal
    func request(method:RequestMethod,URLString:String,parameters:[String:AnyObject]?) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
           
            //1.成功的回调闭包
        let successCallBack = { (task:NSURLSessionDataTask,result:AnyObject) -> Void in
            
                    //将结果发送给订阅者
                    subscriber.sendNext(result)
                    
                    //完成
                    subscriber.sendCompleted()
                }
                
          
            
            //2.失败的回调闭包
            let failureCallBack = { (task:NSURLSessionDataTask,error:NSError) -> Void in
                
                print(error)
                
                subscriber.sendError(error)
            }
            
            
            //3.根据方法，选择调用不同的网络方法
            //if method ＝＝ RequestMethod.GET
            if method == .GET{
                
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }else{
                    self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
                }
            
            return nil
        })

    }
    
    
}
